package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.mapper.TravelContentMapper;
import cn.wolfcode.luowowo.article.mapper.TravelMapper;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper travelContentMapper;

    public PageInfo query(TravelQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public Travel get(Long id) {

        return travelMapper.selectByPrimaryKey(id);
    }

    public TravelContent getContent(Long id) {

        return travelContentMapper.selectByPrimaryKey(id);
    }

    public List<Travel> listViewnumTop3(Long id) {

        return travelMapper.selectViewnumTop3(id);
    }

    public AjaxResult saveOrUpdate(Travel travel) {

        //设置摘要
        String content = travel.getTravelContent().getContent();
        if (content.length()>200){
            travel.setSummary(content.substring(0,200));
        }else {
            travel.setSummary(content);
        }

        //最后更新时间
        travel.setLastUpdateTime(new Date());

        if (travel.getId() == null){

            //创建时间
            travel.setCreateTime(new Date());
            //假装审核通过,设置发布时间
            travel.setState(Travel.STATE_RELEASE);
            travel.setReleaseTime(new Date());
            travelMapper.insert(travel);
            //新增内容
            TravelContent travelContent = travel.getTravelContent();
            travelContent.setId(travel.getId());
            travelContentMapper.insert(travelContent);

        }else {

            travelMapper.updateByPrimaryKey(travel);
            //修改内容
            TravelContent content1 = travel.getTravelContent();
            content1.setId(travel.getId());
            travelContentMapper.updateByPrimaryKey(content1);
        }

        return new AjaxResult().addData(travel.getId());
    }

    public List<Travel> list() {
        return travelMapper.selectAll();
    }
}
